<template>
  <div>
    <el-form class="spuUpdate_form" ref="spuUpdateFormRef" label-width="100">
      <el-form-item label="SKU名称">
        <el-input
          v-model="ADD_SKU_PARAMS.skuName"
          placeholder="请输入SKU名称"
        />
      </el-form-item>

      <el-form-item label="价格(元)">
        <el-input
          v-model="ADD_SKU_PARAMS.price"
          placeholder="请输入价格(元)"
          type="number"
        />
      </el-form-item>

      <el-form-item label="重量(克)">
        <el-input
          v-model="ADD_SKU_PARAMS.weight"
          placeholder="请输入重量(克)"
          type="number"
        />
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          v-model="ADD_SKU_PARAMS.skuDesc"
          placeholder="请输入SPU描述"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form :inline="true" class="cateSelect_section">
          <el-form-item
            :label="PLATE_ATTR.catename"
            v-for="PLATE_ATTR in ALL_PLATE_ATTR"
            :key="PLATE_ATTR.id"
            style="margin-bottom: 10px"
          >
            <el-select
              :placeholder="`请选择${PLATE_ATTR.catename}`"
              clearable
              :disabled="false"
              v-model="ALL_PLATE_ATTR_SELECT[PLATE_ATTR.id]"
            >
              <template v-for="item in PLATE_ATTR.attrValueList" :key="item.id">
                <el-option :label="item.valueName" :value="item.id" />
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form :inline="true" class="cateSelect_section">
          <el-form-item
            :label="SALE_ATTR.saleAttrName"
            v-for="SALE_ATTR in spuFormData.spuSaleAttrList"
            :key="SALE_ATTR.id"
            style="margin-bottom: 10px"
          >
            <el-select
              :placeholder="`请选择${SALE_ATTR.saleAttrName}`"
              clearable
              :disabled="false"
              v-model="SPU_SALE_ATTR_SELECT[SALE_ATTR.id]"
            >
              <template
                v-for="item in SALE_ATTR.supSaleAttrValueList"
                :key="item.id"
              >
                <el-option :label="item.saleAttrValueName" :value="item.id" />
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片名称">
        <el-table
          :data="fileList"
          stripe
          border
          ref="TABLE_REF"
          @select="handleSelectionChange"
          @row-click="SELECT_DEFAUTL_IMG"
        >
          <el-table-column
            label="序号"
            width="100"
            type="selection"
            align="center"
          />

          <el-table-column prop="url" label="图片">
            <template #default="{ row }">
              <myImg :scr="row.url"></myImg>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="名称" />

          <el-table-column label="操作" fixed="right">
            <template #default="{ row }">
              <!-- type="primary" -->
              <el-button
                type="primary"
                size="small"
                v-if="row.url == ADD_SKU_PARAMS.skuDefaultImg"
              >
                默认图片
              </el-button>
              <el-button size="small" @click="SELECT_DEFAUTL_IMG(row)" v-else>
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="save_btns" style="margin-top: 10px">
          <el-button type="primary" size="default" @click="confirmClick">
            保存
          </el-button>

          <el-button size="default" @click="cancelClick">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
export default {
  name: 'skuUpdate',
}
</script>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  resIdBySpuImgList,
  resIdBySpuAttrList,
  reqAddOrUpdateSPU,
  resHasAttribute,
} from '@/api/product'
import type { Spu } from '@/api/product/type'
import type { UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
const props = defineProps(['formType', 'updateData'])

watch(
  () => props.formType,
  (newValue, oldValue) => {
    if (newValue == 'ADD_SKU') {
      initPageData()
      Object.assign(spuFormData, props.updateData)
      initPageReq()
      console.log('updateData', newValue, oldValue)
    }
  },
)

const emit = defineEmits(['cancelUpdate', 'confirmUpdate'])

let TABLE_REF = ref()

let ALL_PLATE_ATTR = ref<any>([])
let ALL_PLATE_ATTR_SELECT = reactive<any>({})
let SPU_SALE_ATTR_SELECT = reactive<any>({})
const ADD_SKU_PARAMS_INIT = {
  category3Id: '',
  spuId: '',
  tmId: '',
  skuName: '',
  price: '',
  weight: '',
  skuDesc: '',
  skuDefaultImg: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
}
let ADD_SKU_PARAMS = reactive<any>({ ...ADD_SKU_PARAMS_INIT })
const spuFormData_init = {
  id: '',
  spuName: '',
  description: '',
  category: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
}
let spuFormData = reactive<Spu>({ ...spuFormData_init })

let fileList = ref<UploadUserFile[]>([])

const initPageReq = async () => {
  let id: any = spuFormData.id
  let result4: any = await resHasAttribute({
    pageNo: 1,
    limit: 10,
  })
  if (result4.code == 200) {
    ALL_PLATE_ATTR.value = result4.data
    initAllPlateAttr()
  }

  Object.assign(ADD_SKU_PARAMS, {
    category3Id: spuFormData.category3Id,
    spuid: spuFormData.id,
    tmId: spuFormData.tmId,
  })

  if (id > 0) {
    let result1: any = await resIdBySpuAttrList(id)

    if (result1.code == 200) {
      spuFormData.spuSaleAttrList = result1.data
      initSpuSaleAttr()
    }
    let result: any = await resIdBySpuImgList(id)
    if (result.code == 200) {
      //   spuFormData.spuImageList = result.data
      initFileList(result.data)
    }
  }
}

const initAllPlateAttr = () => {
  ALL_PLATE_ATTR.value.forEach((ATTR) => {
    ALL_PLATE_ATTR_SELECT[ATTR.id] = ''
  })
}

const initSpuSaleAttr = () => {
  spuFormData.spuSaleAttrList.forEach((ATTR) => {
    SPU_SALE_ATTR_SELECT[ATTR.id] = ''
  })
}

const initFileList = (data) => {
  if (data.length > 0) {
    fileList.value = data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  } else {
    fileList.value = []
  }
}

const initPageData = () => {
  ALL_PLATE_ATTR.value = []
  fileList.value = []
  ALL_PLATE_ATTR_SELECT = {}
  SPU_SALE_ATTR_SELECT = {}
  Object.assign(ADD_SKU_PARAMS, {
    ...ADD_SKU_PARAMS_INIT,
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  })
  Object.assign(spuFormData, {
    ...spuFormData_init,
    spuSaleAttrList: [],
    spuImageList: [],
  })
}
const getUpdateData = () => {
  let skuAttrValueList: any = []
  let skuSaleAttrValueList: any = []
  for (const key in ALL_PLATE_ATTR_SELECT) {
    skuAttrValueList.push({
      attrId: key,
      valueId: ALL_PLATE_ATTR_SELECT[key],
    })
  }
  for (const key in SPU_SALE_ATTR_SELECT) {
    skuSaleAttrValueList.push({
      saleAttrId: key,
      saleAttrValueId: SPU_SALE_ATTR_SELECT[key],
    })
  }
  Object.assign(ADD_SKU_PARAMS, {
    category3Id: spuFormData.category3Id,
    spuid: spuFormData.id,
    tmId: spuFormData.tmId,
    skuAttrValueList,
    skuSaleAttrValueList,
  })
}
const confirmClick = async () => {
  getUpdateData()
  let result: any = await reqAddOrUpdateSPU(spuFormData)
  let type = '添加'
  //   if (spuFormData.id) {
  //     type = '修改'
  //   }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
    initPageData()
    emit('confirmUpdate', spuFormData)
  } else {
    ElMessage({
      type: 'error',
      message: `${type}失败`,
    })
  }
}

const cancelClick = () => {
  initPageData()
  emit('cancelUpdate')
}

const SELECT_DEFAUTL_IMG = (row) => {
  ADD_SKU_PARAMS.skuDefaultImg = row.url
  TABLE_REF.value!.clearSelection()
  TABLE_REF.value!.toggleRowSelection(row, true)
}

const handleSelectionChange = (_rows, row) => {
  SELECT_DEFAUTL_IMG(row)
}
</script>

<style scoped lang="scss">
.tag_row {
  display: flex;
  align-items: center;
}

.cateSelect_section .el-select {
  --el-select-width: 220px;
}
</style>
